package com.athuahua.spzx.service.impl;

import cn.hutool.core.date.DateTime;
import com.athuahua.spzx.dto.system.AssginMenuDto;
import com.athuahua.spzx.deprecated_entity.system.SysMenuHasChildren;
import com.athuahua.spzx.service.SysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.SysRoleMenu;
import com.athuahua.spzx.service.SysRoleMenuService;
import com.athuahua.spzx.mapper.SysRoleMenuMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author huahua
* @description 针对表【sys_role_menu(角色菜单)】的数据库操作Service实现
* @createDate 2024-07-24 09:54:31
*/
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu>
    implements SysRoleMenuService{

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {
        //查询所以菜单
        List<SysMenuHasChildren> sysMenuList = sysMenuService.findNodes();
        //查询角色分配过的菜单id
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(
                new LambdaQueryWrapper<SysRoleMenu>()
                        .eq(SysRoleMenu::getRoleId, roleId)
                        .eq(SysRoleMenu::getIsHalf,0)
                        .select(SysRoleMenu::getMenuId)
        );
        //只保留MenuId的集合
        List<Long> roleMenuIds = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenus) {
            roleMenuIds.add(sysRoleMenu.getMenuId());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("sysMenuList", sysMenuList);
        map.put("roleMenuIds", roleMenuIds);

        return map;
    }

    @Override
    public void doAssign(AssginMenuDto assginMenuDto) {
        //先删除原有所有角色菜单关系
        sysRoleMenuMapper.delete(
                new LambdaQueryWrapper<SysRoleMenu>()
                       .eq(SysRoleMenu::getRoleId, assginMenuDto.getRoleId())

        );


        //添加新的角色菜单关系
        for (Map<String, Number> map : assginMenuDto.getMenuIdList()) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(assginMenuDto.getRoleId());
            sysRoleMenu.setMenuId(map.get("id").longValue());
            sysRoleMenu.setIsHalf(map.get("isHalf").intValue());
            sysRoleMenu.setCreateTime(new DateTime());
            sysRoleMenu.setUpdateTime(new DateTime());
            sysRoleMenuMapper.insert(sysRoleMenu);
        }
    }
}




